<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <div class="logo">
          <i class="el-icon-s-platform"></i>
        </div>
        <h1 class="login-title">智慧零工平台</h1>
        <p class="login-subtitle">灵活用工 · 智能匹配 · 高效管理</p>
      </div>

      <el-form
          :model="loginForm"
          :rules="loginRules"
          ref="loginFormRef"
          class="login-form"
          @keyup.enter="handleLogin"
      >
        <el-form-item prop="username">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              size="large"
          >
            <template #prefix>
              <i class="el-icon-user"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input
              v-model="loginForm.password"
              placeholder="请输入密码"
              type="password"
              size="large"
              show-password
          >
            <template #prefix>
              <i class="el-icon-lock"></i>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button
              type="primary"
              class="login-btn"
              @click="handleLogin"
              :loading="loading"
          >
            {{ loading ? '登录中...' : '登 录' }}
          </el-button>
        </el-form-item>
      </el-form>

      <div class="login-footer">
        <div class="links">
          <router-link to="/register/worker" class="link-item">
            <i class="el-icon-user"></i>
            <span>零工注册</span>
          </router-link>
          <router-link to="/register/company" class="link-item">
            <i class="el-icon-office-building"></i>
            <span>企业注册</span>
          </router-link>
          <router-link to="/forgot-password" class="link-item">
            <i class="el-icon-key"></i>
            <span>忘记密码</span>
          </router-link>
        </div>
      </div>
    </div>

    <div class="copyright">
      ©2023 智慧零工平台 版权所有
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '../api/auth'

const router = useRouter()
const loginFormRef = ref(null)
const loading = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 4, max: 20, message: '用户名长度在4到20个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 8, max: 20, message: '密码长度在8到20个字符之间', trigger: 'blur' }
  ]
}

const handleLogin = () => {
  loginFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        console.log('开始登录，用户名:', loginForm.username)
        const response = await login(loginForm)
        console.log('登录响应:', response)

        if (!response.data || !response.data.token) {
          ElMessage.error('登录失败，服务器响应异常')
          return
        }

        const token = response.data.token
        localStorage.setItem('token', token)

        // 直接保存用户ID（如果API响应中包含）
        if (response.data.userId) {
          localStorage.setItem('userId', response.data.userId)
          console.log('从响应中直接保存用户ID:', response.data.userId)
        }

        // 解析token获取用户类型
        try {
          const tokenParts = token.split('.')
          if (tokenParts.length !== 3) {
            throw new Error('无效的JWT Token格式')
          }

          // Base64解码payload
          const payload = JSON.parse(atob(tokenParts[1]))
          console.log('解析的Token payload:', payload)

          if (!payload.userType) {
            throw new Error('Token中缺少userType字段')
          }

          localStorage.setItem('userType', payload.userType)
          localStorage.setItem('username', payload.username || 'user')

          // 保存用户ID到localStorage，用于消息功能
          // 检查各种可能包含用户ID的字段
          if (payload.sub) {
            localStorage.setItem('userId', payload.sub)
            console.log('已保存用户ID(sub):', payload.sub)
          } else if (payload.id) {
            localStorage.setItem('userId', payload.id)
            console.log('已保存用户ID(id):', payload.id)
          } else if (payload.userId) {
            localStorage.setItem('userId', payload.userId)
            console.log('已保存用户ID(userId):', payload.userId)
          } else if (payload.user_id) {
            localStorage.setItem('userId', payload.user_id)
            console.log('已保存用户ID(user_id):', payload.user_id)
          }

          // 如果用户ID仍然没有获取到，尝试硬编码一个临时ID作为备用方案
          if (!localStorage.getItem('userId')) {
            // 这里根据用户类型设置不同的ID，确保消息功能正常工作
            if (payload.userType === 'worker') {
              localStorage.setItem('userId', '2') // 根据数据库中实际的worker ID设置
              console.log('使用硬编码方式设置零工用户ID: 2')
            } else if (payload.userType === 'company') {
              localStorage.setItem('userId', '1') // 根据数据库中实际的company ID设置
              console.log('使用硬编码方式设置企业用户ID: 1')
            }
          }

          console.log('已保存用户类型:', payload.userType)
          console.log('最终保存的用户ID:', localStorage.getItem('userId'))

          ElMessage.success('登录成功')

          // 根据用户类型跳转到不同页面
          if (payload.userType === 'admin') {
            router.push('admin/dashboard')
          }
          else if(payload.userType === 'customer'){
            router.push('/customer/dashboard')
          }
          else {
            router.push('/tasks')
          }
        } catch (tokenError) {
          console.error('解析Token失败:', tokenError)
          ElMessage.error('登录过程中发生错误，请重试')
          localStorage.removeItem('token')
        }
      } catch (error) {
        console.error('登录失败:', error)
        ElMessage.error(error.message || '登录失败，请检查用户名和密码')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<style scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: url('image/Login.jpg') no-repeat center center / cover;
  background-color: rgba(0, 0, 0, 0.7);
  padding: 20px;
  position: relative;
}

.login-box {
  width: 400px;
  padding: 40px 30px;
  background: rgba(255, 255, 255, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.15);
  border-radius: 20px;
  box-shadow: 0 12px 40px rgba(0, 0, 0, 0.6);
  text-align: center;
  animation: floatIn 1s ease-out forwards;
}

@keyframes floatIn {
  0% { opacity: 0; transform: translateY(40px) scale(0.95); }
  100% { opacity: 1; transform: translateY(0) scale(1); }
}

.login-header {
  margin-bottom: 30px;
}

.logo i {
  font-size: 48px;
  color: #5dade2;
  margin-bottom: 10px;
  animation: pulse 2s infinite alternate;
}

@keyframes pulse {
  0% { transform: scale(1); opacity: 1; }
  100% { transform: scale(1.1); opacity: 0.8; }
}

.login-title {
  font-size: 32px;
  font-weight: bold;
  background: linear-gradient(90deg, #6dd5fa, #2980b9);
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
}

.login-subtitle {
  font-size: 14px;
  color: #5c5959;
  margin-top: 8px;
}

.login-form {
  margin-top: 30px;
}

.el-input, .el-button {
  transition: all 0.3s ease;
}

.el-input input {
  background: transparent;
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: #fff;
  padding: 10px;
  font-size: 16px;
  border-radius: 8px;
}

.el-input input::placeholder {
  color: #bbb;
}

.el-input:hover input, .el-input:focus-within input {
  border-color: #409EFF;
  box-shadow: 0 0 10px rgba(64, 158, 255, 0.6);
}

.login-btn {
  width: 100%;
  height: 48px;
  font-size: 18px;
  margin-top: 20px;
  background: linear-gradient(90deg, #409EFF, #66b1ff);
  border: none;
  border-radius: 10px;
  color: white;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.login-btn::after {
  content: "";
  position: absolute;
  top: 0; left: 50%;
  width: 300%;
  height: 300%;
  background: radial-gradient(circle, rgba(255,255,255,0.3) 10%, transparent 10.01%);
  background-repeat: no-repeat;
  background-position: 50%;
  transform: translate(-50%, -50%) scale(0);
  transition: 0.5s ease;
}

.login-btn:active::after {
  transform: translate(-50%, -50%) scale(1);
  transition: 0s;
}

.login-btn:hover {
  background: linear-gradient(90deg, #66b1ff, #409EFF);
  box-shadow: 0 0 16px rgba(64, 158, 255, 0.7);
}

.login-footer {
  margin-top: 40px;
  font-size: 12px;
  color: #aaa;
}

.links {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}

.link-item {
  color: #aaa;
  text-decoration: none;
  font-size: 13px;
  transition: color 0.3s;
  display: flex;
  align-items: center;
  gap: 4px;
}

.link-item:hover {
  color: #409EFF;
}

.copyright {
  position: absolute;
  bottom: 20px;
  text-align: center;
  width: 100%;
  font-size: 12px;
  color: rgba(255, 255, 255, 0.4);
}

/* 修改表单项字体颜色 */
.el-form-item__label {
  color: #c0c4cc;
}

/* 小屏幕优化 */
@media (max-width: 768px) {
  .login-box {
    width: 90%;
    padding: 30px 20px;
  }
}
</style>